// pmtlogger.c

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>

#define PMT_SERVER_SOCKET "/tmp/.listen.camd.socket"

void utils_dump(char *label, unsigned char *data, int len)
{
	int i;
	printf(label);
	for(i = 0; i < len; i++) {
		printf("%02X ", data[i]);
        }
	printf(" [len=%02X]\n", len);
}

int main(int argc,char **argv)
{
	int fifo;
	struct sockaddr_un saddr, caddr;
	unsigned char pmtbuf[4096];
	int pmtlen;

	/* socket init */
	saddr.sun_family = AF_UNIX;
	strncpy(saddr.sun_path, PMT_SERVER_SOCKET, 107);
	saddr.sun_path[107] = '\0';
	if((fifo = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
		printf("socket error (errno=%d)\n", errno);
		perror("");
		return 1;
	}
	if (connect(fifo, (struct sockaddr *)&saddr, sizeof(saddr)) < 0) {
		printf("socket connect error (errno=%d)\n", errno);
		perror("");
		return 2;
	}
	printf("Waiting for PMT on %s ...\n", saddr.sun_path);

	while (1)
	{
		pmtlen = recv(fifo, pmtbuf, sizeof(pmtbuf), 0);
		if (pmtlen < 0)
		{
			printf("recv error (errno=%d)\n", errno);
			perror("");
			return 3;
		}
		if (pmtlen == 0)
		{
			printf("connection closed by server.\n");
			return 0;
		}
		utils_dump("PMT: ", pmtbuf, pmtlen);
	}
	close(fifo);
	return 0;
}

